﻿using UnityEngine;
using UnityEngine.AI;

public class Test2_Hz152 : MonoBehaviour
{
    public NavMeshAgent navAgent; // 用于寻路
    public float moveSpeed = 70f; // 移动速度（单位：单位/秒）

    private Camera mainCamera;
    private Vector3[] path;       // 存储寻路得到的路径点
    private int currentTargetIndex; // 当前要走向的路径点索引
    private bool isMoving = false;  // 是否正在移动

    private void Start()
    {
        mainCamera = Camera.main;
        if (mainCamera == null)
        {
            Debug.LogError("Main camera not found. Make sure a camera has the 'MainCamera' tag.");
        }

        if (navAgent != null)
        {
            navAgent.updatePosition = false;  // 我们手动设置位置
            navAgent.updateRotation = false;  // 我们手动控制旋转
            navAgent.enabled = false;         // 禁用自动导航（我们只用它来计算路径）
        }
        else
        {
            Debug.LogError("NavMeshAgent component not assigned!");
        }
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mouseScreenPosition = Input.mousePosition;
            mouseScreenPosition.z = 10f; 
            Vector3 worldPosition = mainCamera.ScreenToWorldPoint(mouseScreenPosition);

            // 发起寻路请求
            RequestPath(worldPosition);
        }

        // 持续移动
        if (isMoving && path != null && currentTargetIndex < path.Length)
        {
            MoveAlongPath();
        }
    }

    /// <summary>
    /// 请求一条到目标点的路径
    /// </summary>
    /// <summary>
    /// 请求一条到目标点的路径
    /// </summary>
    private void RequestPath(Vector3 targetPosition)
    {
        NavMeshPath newPath = new NavMeshPath();

        //  使用 NavMesh.CalculatePath 静态方法（不是 navAgent 的）
        bool success = NavMesh.CalculatePath(
            transform.position,     // 起点
            targetPosition,         // 终点
            NavMesh.AllAreas,       // 区域掩码（允许通过的区域）
            newPath                 // 输出路径
        );

        if (success && newPath.status == NavMeshPathStatus.PathComplete)
        {
            path = newPath.corners;
            currentTargetIndex = 0;
            isMoving = true;
            Debug.Log("Path calculated with " + path.Length + " corners.");
        }
        else
        {
            Debug.LogWarning("Failed to find a path to the destination.");
            isMoving = false;
        }
    }

    /// <summary>
    /// 沿着路径点移动
    /// </summary>
    private void MoveAlongPath()
    {
        if (path == null || path.Length == 0) return;

        Vector3 targetPoint = path[currentTargetIndex];
        Vector2 direction = (targetPoint - transform.position).normalized;

        //  使用 MoveTowards —— 无惯性、线性移动
        transform.position = Vector2.MoveTowards(
            transform.position,
            targetPoint,
            moveSpeed * Time.deltaTime
        );

        //  手动旋转朝向移动方向
        if (direction.sqrMagnitude > 0.01f)
        {
            float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90f;
            transform.rotation = Quaternion.Euler(0, 0, angle);
        }

        // 到达当前路径点，切换到下一个
        if (Vector2.Distance(transform.position, targetPoint) < 0.1f)
        {
            currentTargetIndex++;

            // 所有点走完，停止移动
            if (currentTargetIndex >= path.Length)
            {
                isMoving = false;
            }
        }
    }
}